<template>
    <div class="intelligentResult">
        <!-- 输入车牌组件 -->
        <CarKey ref="carKey2" @getCarNo="getCarNo"></CarKey>
        <h3 class="pageTitle">智能定责结果</h3>
        <div class="result-sec">
            <p>根据上传的照片判断</p>
            <div class="result-rows">
                <div class="l-c">车牌号</div>
                <div class="r-c" v-model="QZ">{{QZ}}</div>
            </div>
            <div class="result-rows">
                <div class="l-c">违反了</div>
                <div class="r-c">{{resultMsg}}</div>
            </div>
            <div class="duty-sec">
                <div class="duty-l">
                    <h2>全责</h2>
                    <p v-model="QZ">{{QZ}}</p>
                </div>
                <div class="duty-r">
                    <h2>无责</h2>
                    <p v-model="WZ">{{WZ}}</p>
                </div>
            </div>
            <!-- <p class="f012">事故编号：<span>{{accidentNo}}</span></p> -->
            <p class="f012">请将智能责任校验结果告知对方车主，友好协商<br />任意一方对结果有异议，请点击“不同意”，案件将流转至<br />交警远程处理，双方对结果无异议，请点击“同意”</p>
            <p class="f012">注：如任何一方行驶证、驾驶证状态异常，则责任认定需交警重新审核</p>
        </div>
        
        <!-- 查看事故照片 -->
        <div class="checkPicWrap">
            <p class="f012 setWidth">查看事故照片</p>
            <div class="accidentPic">
                <ul class="pciList clearfix">
                    <li v-if="type" v-for="(item,index) in imgList" :key="index">
                        <img :src="item.src" alt="" v-preview="item.src">
                        <p class="p_a">{{item.text}}</p>
                    </li>
                </ul>
            </div>
        </div>

        <!-- B方信息显示区 -->
        <p class="f012 setWidth">驾驶员本人及车辆信息</p>
        <div class="info-sec">
            <div class="info-rows">
                <div>车牌号码</div>
                <div class="wrap-sec w2_4">
                    <input type="text" @click="chooseCarNo" readonly onfocus="this.blur()" unselectable="on" placeholder="请输入车牌" v-model="carNo">
                    <!-- <div class="fun-sec">
                        <span id="camera" class="camera"></span>
                    </div> -->
                    <div class="fun-sec">
                        <input id="camera" capture="camera" accept="image/jpeg,image/jpg" type="file" @change="addImg()" style="display:none">
                        <span class="camera" @click="recognizeCar"></span>
                    </div>
                </div>
            </div>
            <div class="info-rows add-border-top">
                <div>姓名</div>
                <input class="w2_4" type="text" v-model.trim="appliName">
            </div>
            <div class="info-rows add-border-top">
                <div>责任认定</div>
                <input class="w2_4" type="text" readonly onfocus="this.blur()" unselectable="on" v-model="dutyPercentTxt">
            </div>
            <div class="info-rows add-border-top">
                <div>手机号码</div>
                <input class="w2_4" type="tel" maxlength="11" v-model.trim="mobile">
            </div>
            <div class="info-rows add-border-top">
                <div>验证码</div>
                <div class="wrap-sec w2_4">
                    <input class="inputCode" type="tel" maxlength="4" v-model.trim="mobileCode" placeholder="请任意输入4位数字">
                    <button @click="getCode" class="code-btn">{{codeTxt}}</button>
                </div>
            </div>
        </div>   

        <!-- 底部button区 -->
        <div class="bottomBtnSec">
            <!-- <div class="btnRows">
                <button>录入对方信息</button><button>对方扫码录入</button>
            </div>
            <div class="btnRows none">
                <button>不同意</button><button>同意</button>
            </div> -->
            <mu-container class="demo-container">
                <mu-row gutter>
                    <mu-col span="6">
                        <div class="grid-cell">
                            <mu-button @click="chooseResuilt(10)" style="height:.48rem;font-size:.18rem" color="#6794F5" full-width>不同意</mu-button>
                        </div>
                    </mu-col>
                    <mu-col span="6">
                        <div class="grid-cell">
                            <mu-button @click="chooseResuilt(9)" style="height:.48rem;font-size:.18rem" color="#6794F5" full-width>同意</mu-button>
                        </div>
                    </mu-col>
                </mu-row>
            </mu-container>
        </div>
    </div>    
</template>
<script>
import {http} from 'utils/request.js';
import api from '../../api/index.js';
import CarKey from '../../components/carKey/carKey';
import {getImgToken, upLoadImg, getUrlParams, getOCRResult} from 'utils/commonUtil.js';
export default {
    name: "intelligentResult_B",
    data() {
        return {
            carId: '',
            accidentNo: '',
            carNo: '',
            dutyPercent: '',
            dutyPercentTxt: '',
            resultMsg: '', //  事故描述
            QZ: '',  //  全责车牌
            WZ: '', //  无责车牌
            appliName: '',
            mobile: '',
            mobileCode: '',
            type: false,
            imgList: [],  //  照片列表
            timeFlag: true,
            codeTxt: '获取验证码',
            test: 0
        }
    },
    created() {
        // 截取url上面的参数
        // this.carId = getUrlParams('carId');
        // this.accidentNo = getUrlParams('accidentNo');
        // this.fromTo = getUrlParams('fromTo');
        document.title = '智能定责';
        // 截取url上面的参数
        this.carId = this.$route.query.carId;
        this.accidentNo = this.$route.query.accidentNo;
        this.fromTo = this.$route.query.fromTo; 
    },
    mounted() {
        sessionStorage.setItem('accidentNo',this.$route.query.accidentNo);
        this.changeStatus();
        this.queryBInfo();
        this.getAccidentPhotoList();  
        this.geolocation();
    },
    components: {
        CarKey
    },
    computed: {
        
    },
    watch: {
        carNo: 'Listener',
        test: {
            handler(curVal,oldVal){
                if (curVal > 0) {
                    this.$toast.message({
                        message: '您当前位置距离深圳市会展中心' + this.test + '米',
                        color: '#F57979'
                    }); 
                }           
            },
            deep: true, 
        }
    },
    methods: {
        //选择车牌
        chooseCarNo() {
            this.$refs.carKey2.openKey();
        },
        getCarNo(value) {
            this.carNo = value;
            this.$refs.carKey2.closeKey();
        },
        // 监听车牌变化
        Listener() {
            if (this.dutyPercent == 1) {
                this.QZ = this.carNo;
            } else if (this.dutyPercent == 5) {
                this.WZ = this.carNo;
            }
        },
        
        //点击同意或不同意
        chooseResuilt(state) {            
            // if(this.test>5000) {
            //     this.$toast.message({
            //         message: '温馨提示：您当前所处位置距离深圳市会展中心' + this.test + '米，已超出该产品试用范围。',
            //         color: '#F57979'
            //     }); 
            //     return
            // };
            if(!this.checkFormat()) return;
            //保存B方信息
            http.post(api.API_ACCIDENT_UPDATE,{
                carId: this.carId,  //车辆id
                accidentNo: this.accidentNo, //事故编号
                driverName: this.appliName,  // B方姓名
                carNo: this.carNo,  //车牌号
                mobile: this.mobile, //手机
                carStatus: state,  //车辆状态
                fromTo: "0", //是否本方车辆 1 本方 0 对方
                dutyPercent: this.dutyPercent, //责任划分
                isScan: 1
            }).then(((res) => {
                if(res.code=="1") {
                    //点击同意跳转 
                    if(state=="9") {
                        this.$router.push({
                            name:"supplement",
                            query: {
                                accidentNo: this.accidentNo, //事故编号
                                carId: this.carId, 
                                fromTo: 0,   //判断是从a来还是从b来.
                                pageOrignCheng:'b' 
                            }
                        });
                    }else { //不同意
                        this.$router.push("/lastPage");
                    }
                }
            })).catch((error) =>{
                console.log(error);
            });
        },

        // ruankai 
        // 扫码打开页面后，状态更新
        changeStatus() {
            http.post(api.API_SCAN, {
                scanStatus: 1,
                carId: this.carId,
            }).then(((res) => {
                if(res.code == 1) {
                    console.log(res.message);
                    
                } else if (res.code == 0) {
                    this.$toast.message({
                        message: res.message,
                        color: '#F57979'
                    });
                } else {
                    alert ("系统异常")
                }
            })).catch((error) => {
                console.log(error);
            })
        },

        // 获取事故B方的事故相关信息
        queryBInfo() {
            http.post(api.API_ACCIDENT_DETAIL, {
                accidentNo: this.accidentNo
            }).then(((res) => {
                if(res.code == 1) {
                    console.log(res.message);
                    var obj = res.resultObj.carInfoBeans;
                    for (var index = 0; index < obj.length; index++) {
                        if (this.fromTo == obj[index].fromTo) {
                            this.carNo = obj[index].carNo; // B方车牌
                            this.dutyPercent = obj[index].dutyPercent; // 责任比例
                            this.dutyPercentTxt = this.getDutyPercent(this.dutyPercent); // 责任比例汉字说明
                        };
                        if (obj[index].dutyPercent == 1) {
                            this.QZ = obj[index].carNo;
                        } else if (obj[index].dutyPercent == 5) {
                            this.WZ = obj[index].carNo;
                        }
                        
                    }
                    this.resultMsg = res.resultObj.accidentInfoBean.accidentResult;
                } else if (res.code == 0) {
                    this.$toast.message({
                        message: res.message,
                        color: '#F57979'
                    });
                } else {
                    alert ("系统异常")
                }
            })).catch((error) => {
                console.log(error);
            })
        },
        
        // 数据校验
        checkFormat() {

            var reg_mobile = /^1[3,4,5,6,7,8,9]\d{9}$/; // 校验电话号码格式
            //var reg_carNo = /^[\u4e00-\u9fa5][A-Za-z][A-Za-z0-9]{5}$/; // 校验普通蓝牌车，车牌长度为5，注意：新能源车牌应将长度改为6。
            var reg_carNo = /^[\u4e00-\u9fa5][A-Za-z][A-Za-z0-9]/; // 校验车牌，不限长度


            if(!(reg_carNo.test(this.carNo) && (this.carNo.length == 6 || this.carNo.length == 7))) {
                    this.$toast.message({
                    message: '请按照提示输入正确的车牌',
                    color: '#F57979'
                });
                return false;
            };
            if(this.appliName == '') {
                this.$toast.message({
                    message: '请输入姓名',
                    color: '#F57979'
                });
                return false;
            }
            if(!reg_mobile.test(this.mobile)) {
                this.$toast.message({
                    message: '请按照提示输入正确的手机号码',
                    color: '#F57979'
                });
                return false;
            };
            if(this.mobileCode.length!=4) {
                this.$toast.message({
                    message: '请按照提示输入正确的验证码',
                    color: '#F57979'
                });
                return false;
            };
            return true;
        },

        // 获取车辆照片信息
        getAccidentPhotoList() {  
            http.post(api.API_QUERY_PHOTO_LIST, {
                accidentNo: this.accidentNo,
                type: "five"
            }).then(((res) => {
                if(res.code == 1) {
                    let arr = [];                
                    for (var index = 0; index < res.resultObj.length; index++) {   
                        let type = res.resultObj[index].photoType; 
                        arr.push({
                            'src' : res.resultObj[index].photoUrl,
                            'text': this.setText(type)
                        }); 
                    };
                    this.imgList = arr;
                    console.log(this.imgList);
                    this.type = true;
                } else if (res.code == 0) {
                    this.$toast.message({
                        message: res.message,
                        color: '#F57979'
                    });
                } else {
                    alert ("系统异常")
                }
            })).catch((error) => {
                console.log(error);
            })
        },
        setText(obj) {
            if(obj == '01') {
                return '全景照片（车头）';
            } else if (obj == '02') {
                return '全景照片（车尾）';
            } else if (obj == '03') {
                return '近景照片（车头）';
            } else if (obj == '04') {
                return '近景照片（车尾）';
            } else {
                return '其他照片';
            }
        },

        //获取验证码
        getCode() {
            //防止重复提交
            if(!this.timeFlag) return;
            this.timeFlag = false;
            let NUM = 10;
            const timer = setInterval(()=>{
                this.codeTxt = "重新发送("+ NUM + ")";
                if(NUM==0) {
                    this.codeTxt = "重新发送";
                    this.timeFlag = true;
                    clearInterval(timer);
                };
                NUM--;
            },1000);
        },

        // 判断责任比例
        getDutyPercent(e) {
            if(e == "1") {
                return "全责";
            } else if (e == "2") {
                return "主责";
            } else if (e == "3") {
                return "同责";
            } else if (e == "4") {
                return "次责";
            } else if (e == "5") {
                return "无责";
            }
        },

        // 调用摄像头，识别车牌
        recognizeCar() {
            document.querySelector("#camera").click();
        },
        addImg() {
            const params = {};
           params.timestamp = Date.now();
           const file = event.target.files[0];
           params.file = file;
           getImgToken().then(res=>{
                    params.token = res.resultObj;
                    return upLoadImg(params)
            }).then(res=>{
                this.getCarResult(res.key);
            });
        },
        getCarResult(key) {
            getOCRResult("03",key).then((res)=>{
                if(res.code=="1" && res.resultObj && res.resultObj.result) {
                    const result = res.resultObj.result.result;
                    for(var val in result) {
                        if(result[val][0]&&result[val][0][0]) {
                            this.carNo = result[val][0][0];
                        }else{
                            this.$toast.message({
                                message: '无法识别车牌信息',
                                color: '#F57979'
                            });
                        }
                    };
                }
            }).catch((error) =>{
                console.log(error);
            });
        },

        // 事故B方获取定位
        geolocation() {
            let that = this;
            let geolocation = new BMap.Geolocation();            
		    let map = new BMap.Map();		
            let myGeo = new BMap.Geocoder();
            geolocation.getCurrentPosition(function(r) {
                if(this.getStatus() == BMAP_STATUS_SUCCESS) {
                    var pt = r.point;
                    // 根据坐标得到地址描述
                    myGeo.getLocation(pt, function(result) {
                        if(result) {
                            let accidentLng = result.point.lng;  //事故纬度
                            let accidentLat = result.point.lat;  //事故经度
    
                            let A = new BMap.Point(accidentLng, accidentLat);
                            let B = new BMap.Point(114.066337, 22.536516); // 深圳市会展中心经纬度
                            console.log('测试：' + map.getDistance(A,B).toFixed(0));
                            that.test = map.getDistance(A,B).toFixed(0);                             
                        }
                    });	
                } else {
                    alert('百度地图定位获取定位失败。')
                }
		    });
        }
    },
}
</script>

<style lang="scss" scoped>
    @import "~assets/css/mixin.scss";
    .intelligentResult {        
        background: url(../../assets/img/intelligentResultbg.png) no-repeat;
        background-size: 100% auto;
        background-color: rgb(245, 246, 248);
    }
    .pageTitle {
        text-align: center;
        font-size: 0.2rem;
        line-height: 0.5rem;
        color: #fff;
    }
    .result-sec {
        width: 3.45rem;
        height: auto;
        margin: 0 auto;
        padding: 0.1rem;
        font-size: 0.16rem;
        border-radius: 0.05rem;
        background-color: #fff;
    }
    .result-rows {
        display: flex;
        justify-content: space-between;
        margin: 0.1rem 0;
    }
    .l-c {
        width: auto;
    }
    .r-c {
        width: 2.6rem;
        color: #6794F5;
    }
    .duty-sec {
        width: 3.25rem;
        height: 0.89rem;
        margin: 0 auto;
        text-align: center;
        display: flex;
        justify-content: space-between;
        border-radius: 0.05rem;
        overflow: hidden;
    }
    .duty-r, 
    .duty-l {
        width: 50%;
    }
    .duty-l {
        background-color: #6794F5;
        color: #fff;
    }
    .duty-r {
        background-color: #DFE5F0;
        color: #A8B0BE;
    }
    .duty-sec h2 {
        font-size: 0.22rem;
        line-height: 0.5rem;
        margin: 0.08rem 0 0 0;
    }
    .duty-sec p {
        font-size: 0.16rem;
    }
    .f012 {
        font-size: 0.12rem;
        color: #8D9093;
        margin: 0.1rem 0;
    }
    .info-sec {
        background-color: #fff;
        padding: 0 0 0 0.15rem;
        input {
            color:#8D9093;
        }
    }
    .info-sec .info-rows {
        padding: 0 0.15rem 0 0;
        font-size: 0.16rem;
    }
    .info-sec .info-rows input {
        border: none;
        height: 0.5rem;
    }
    .setWidth {
        width: 3.45rem;
        margin: 0.1rem auto;
    }
    .add-border-top {
        border-top: 1px solid #D8D8D8;
    }
    .fun-sec {
        display: flex;
    }
    // .fun-sec span {
    //     display: inline-block;
    //     width: 0.22rem;
    //     height: 0.2rem;
        
    // }
    .camera {
        background: url(../../assets/img/camera.png) no-repeat;
        background-size: 100% 100%;
        display: inline-block;
        width: 0.22rem;
        height: 0.2rem;
    }
    .arrows {
        background: url(../../assets/img/arrows.png) no-repeat;
        background-size: 100% 100%;
    }
    .wrap-sec {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 100%;
    }   
    .w2_4 {
        width: 2.4rem;
    }
    .f-t {
        font-weight: 700;
    }

    .bottomBtnSec{
        margin: rem(15) rem(7);
    }

    .loading-container {
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.2);
        display: flex;
        justify-content: space-around;
        align-items: center;
        position: absolute;
        top: 0;
        left: 0;
        text-align: center;
        display: none;
    }
    .loading-Wrap {
        width: 2.7rem;
        height: 3.4rem;
        background-color: #fff;
        border-radius: 0.05rem;
        margin: 0 auto;
    }
    .loading-img {
        display: inline-block;
        width: 1.88rem;
        height: 2.2rem;
        margin: 0.2rem auto;
    }
    .loading-Wrap .f015 {
        font-weight: 700;
    }
    .f015 {
        font-size: 0.15rem;
        color: #3D4042;
    }
    .f012 {
        font-size: 0.12rem;
    }
    .fc_AEB3B7 {
        color: #AEB3B7;
    }

    .accidentPic {
        width: 100%;
        height: 2.56rem;
        background-color: #fff;
    }
    .pciList {
        width: 100%;
        height: 100%;
        padding: 0 0.15rem;
    }
    .pciList li {
        width: 1.05rem;
        height: 1.05rem;
        border-radius: 0.05rem;
        background-color: #D8D8D8;
        position: relative;
        float: left;
        margin: 0.15rem 0 0;
        border-radius: 6px;
        overflow: hidden;
    }    
    .pciList li:nth-child(2),
    .pciList li:nth-child(5) {
        margin: 0.15rem 0.15rem 0;
    }
    .pciList .p_a {
        font-size: 0.12rem;
        line-height: 0.25rem;
        color: #fff;
        text-align: center;
        width: 100%;
        position: absolute;
        bottom: 0;
        left: 0;
    }
    .pciList img {
        width: 100%;
        height: auto;
    }
    .hide {
        opacity: 0;
    }

    .code-btn {
        display: inline-block;
        width: 0.8rem;
        height: 0.34rem;
        background-color: #F0F0F0;
        border-radius: 4px;
        color: #CBCBCB;
        font-size: 0.12rem;
        outline: none;
        border: none;
    }
    .codePicSec {
        width: 100%;
        height: auto;
        margin: 0.4rem 0;
    }
    .codePic {
        width: 2.62rem;
        height: 2.62rem;
        margin: 0 auto;
        background-color: #fff;
    }
    .codePicSec .f012 {
        text-align: center;
        line-height: 0.34rem;
    }
    .btnRows {
        display: flex;
        justify-content: space-around;
        text-align: center;
        height: 0.8rem;
    }
    .btnRows button {
        width: 1.66rem;
        height: 0.48rem;
        background-color: #6794F5;
        outline: none;
        border: none;
        border-radius: 4px;
        color: #fff;
        font-size: 0.18rem;
    }
    .none {
        display: none;
    }
    .inputCode {
        width: 1.5rem;
    }
</style>

